package com.example.myapplication.module1.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.location.LocationClientOption.LocationMode
import com.example.myapplication.ConstantsData
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivitySignInBinding
import com.example.myapplication.entity.CustomerInfoBean
import com.example.myapplication.module1.presenter.SignInPresenter
import com.example.myapplication.soaprequest.SoapEnvelop
import com.example.myapplication.soaprequest.request.RegisterWriteRequest
import com.example.myapplication.soaprequest.request.SoapRequestBody
import com.example.myapplication.widget.CustomerToolbar
import com.example.mylibrary.base.BaseMvpActivity
import com.example.mylibrary.utils.UiTools
import com.lxj.xpopup.impl.LoadingPopupView
import com.tbruyelle.rxpermissions2.RxPermissions


/**
 * 签到
 */
class SignInActivity : BaseMvpActivity<SignInActivity, SignInPresenter, ActivitySignInBinding>() {
    private val registerWriteRequest = RegisterWriteRequest()
    private val soapRequestBody = SoapRequestBody()
    val soapEnvelop = SoapEnvelop()
    lateinit var loadPopup: LoadingPopupView
    var lng = "39.963175"   // 经度
    var lat = "116.400244"  // 纬度

    private val rxPermissions: RxPermissions by lazy {
        RxPermissions(this)
    }

    override fun getBinding(): ActivitySignInBinding {
        return ActivitySignInBinding.inflate(layoutInflater)
    }

    override fun getPresenter(): SignInPresenter {
        return SignInPresenter()
    }

    @SuppressLint("CheckResult")
    override fun initData() {

        rxPermissions.request(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        ).subscribe {
            if (it) {
                initLocationOption()
            } else {
                UiTools.showToast("无法获取位置权限")
            }
        }


    }

    override fun initView() {
        loadPopup = builder.asLoading("加载中...")
        viewBinding.clToolbar.clickListener = object : CustomerToolbar.ClickListener {
            override fun onBackListener() {
                finish()
            }

            override fun onRightListener() {
                // 保存签到信息
                saveSignInfo()
            }
        }
        // 初始化点击事件
        viewBinding.tvChooseCustomer.setOnClickListener(this)
        viewBinding.ivDelete.setOnClickListener(this)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tvChooseCustomer -> {
                // 选择客户信息
                startNextActivityForResult(
                    this,
                    ConstantsData.CHOOSE_CUSTOMER_INFO,
                    null,
                    ChooseCustomerActivity::class.java
                )
            }
            R.id.ivDelete -> {
                // 清除客户信息
                registerWriteRequest.clientid = ""
                viewBinding.tvChooseCustomer.text = UiTools.getString(R.string.chooseCustomer)
            }
        }
    }

    private fun saveSignInfo() {
        if (viewBinding.rbOutside.isChecked) {
            registerWriteRequest.types = "1"
        }
        if (viewBinding.rbToWork.isChecked) {
            registerWriteRequest.types = "2"
        }
        if (viewBinding.rbOffWork.isChecked) {
            registerWriteRequest.types = "3"
        }
        registerWriteRequest.ext = ""
        registerWriteRequest.fs = ""
        registerWriteRequest.memo = viewBinding.etSignInContent.text.toString()
        registerWriteRequest.address = viewBinding.tvAddress.text.toString()
        registerWriteRequest.jd = lng
        registerWriteRequest.wd = lat

        soapRequestBody.value = registerWriteRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.saveSignIn(soapEnvelop)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                // 选择客户返回数据
                ConstantsData.CHOOSE_CUSTOMER_INFO -> {
                    val parcelableExtra =
                        data?.getParcelableExtra<CustomerInfoBean>("customerInfoBean")
                    registerWriteRequest.clientid = parcelableExtra?.id.toString()
                    viewBinding.tvChooseCustomer.text = parcelableExtra?.cname
                }
            }
        }
    }


    fun showLoad() {
        loadPopup.show()
    }

    fun dismissLoad() {
        loadPopup.dismiss()
    }

    // 定位信息
    private fun initLocationOption() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        val locationClient = LocationClient(applicationContext)
        //声明LocationClient类实例并配置定位参数
        val locationOption = LocationClientOption()

        //注册监听函数
        locationClient.registerLocationListener(object : BDAbstractLocationListener() {

            override fun onReceiveLocation(location: BDLocation) {
                //获取纬度信息
                lat = "${location.latitude}"
                //获取经度信息
                lng = "${location.longitude}"
                // 获取地址描述
                viewBinding.tvAddress.text = location.addrStr
                locationClient.stop()
            }
        })
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.locationMode = LocationMode.Hight_Accuracy
        //可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("gcj02")
        //可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(1000)
        //可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true)
        //可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true)
        //可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false)
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.isLocationNotify = true
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true)
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true)
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true)
        //可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false)
        //可选，默认false，设置是否开启Gps定位
        locationOption.isOpenGps = true
        //可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false)
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode()
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT)
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.locOption = locationOption
        //开始定位
        locationClient.start()
    }

    fun saveResult(result: String) {
        UiTools.showToast(R.string.saveSuccess)
        finish()
    }


}
